// src/components/User/TorrentHistory.jsx
import { useState, useEffect } from 'react'
import {Table, Tag, Button, Alert, Select, Space, Row, Col, Card, Statistic, Progress, Modal, message} from 'antd'
import { Pie } from '@ant-design/plots'
import { userAPI } from '@/api/user'
import { ExclamationCircleOutlined } from '@ant-design/icons'

// 格式化字节数为人类可读格式
const formatBytes = (bytes, decimals = 2) => {
  if (!bytes || bytes === 0) return '0 Bytes'

  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']

  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

// 格式化小时数为人类可读格式
const formatHours = (hours) => {
  if (!hours) return '0小时'

  if (hours < 24) {
    return `${hours.toFixed(1)}小时`
  }

  const days = hours / 24
  if (days < 7) {
    return `${days.toFixed(1)}天`
  }

  const weeks = days / 7
  return `${weeks.toFixed(1)}周`
}

// 默认虚拟数据（用于连接失败时展示）
const DEFAULT_SEEDING_DATA = {
  total_seeding: 12,
  total_downloading: 3,
  total_uploaded: 10737418240,  // 10 GB
  total_downloaded: 5368709120, // 5 GB
  global_share_ratio: 2.0,
  seeding_list: [
    {
      torrentId: 101,
      torrentName: "示例电影 1080p",
      uploaded: 2147483648,
      downloaded: 1073741824,
      shareRatio: 2.0,
      status: "seeding",
      seedingTime: 72
    },
    {
      torrentId: 102,
      torrentName: "开源软件合集",
      uploaded: 5368709120,
      downloaded: 1073741824,
      shareRatio: 5.0,
      status: "seeding",
      seedingTime: 240
    },
    {
      torrentId: 103,
      torrentName: "经典音乐专辑",
      uploaded: 1073741824,
      downloaded: 1073741824,
      shareRatio: 1.0,
      status: "downloading",
      seedingTime: 12
    },
    {
      torrentId: 104,
      torrentName: "学习教程合集",
      uploaded: 2147483648,
      downloaded: 5368709120,
      shareRatio: 0.4,
      status: "completed",
      seedingTime: 48
    },
    {
      torrentId: 105,
      torrentName: "高清纪录片",
      uploaded: 1073741824,
      downloaded: 1073741824,
      shareRatio: 1.0,
      status: "stopped",
      seedingTime: 0
    }
  ]
}

export default function TorrentHistory() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const [filter, setFilter] = useState({
    status: 'all',
    pagination: { current: 1, pageSize: 10 }
  })

  const [data, setData] = useState({
    list: [],
    total: 0
  })

  const [seedingStats, setSeedingStats] = useState(null)
  const [allTorrents, setAllTorrents] = useState([]) // 存储所有状态的种子
  const [shareRatioStatus, setShareRatioStatus] = useState(null)

  // 定义表格列
  const columns = [
    {
      title: '种子名称',
      dataIndex: 'torrentName',
      render: (text, record) => (
          <Button
              type="link"
              onClick={() => window.open(`/torrent/${record.torrentId}`)}
              style={{ paddingLeft: 0 }}
          >
            {text}
          </Button>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: status => (
          <Tag color={
            status === 'seeding' ? 'green' :
                status === 'downloading' ? 'blue' :
                    status === 'completed' ? 'cyan' : 'gray'
          }>
            {{
              seeding: '做种中',
              downloading: '下载中',
              completed: '已完成',
              stopped: '已停止'
            }[status] || status}
          </Tag>
      )
    },
    {
      title: '上传量',
      dataIndex: 'uploaded',
      render: bytes => formatBytes(bytes)
    },
    {
      title: '下载量',
      dataIndex: 'downloaded',
      render: bytes => formatBytes(bytes)
    },
    {
      title: '分享率',
      dataIndex: 'shareRatio',
      render: ratio => (
          <Tag color={ratio >= 1 ? 'green' : 'red'}>
            {ratio?.toFixed(2) || '0.00'}
          </Tag>
      )
    },
    {
      title: '做种时长',
      dataIndex: 'seedingTime',
      render: hours => formatHours(hours)
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <Button
              type="link"
              onClick={() => handleUpdateSeedingStatus(record.torrentId)}
              disabled={record.status === 'stopped'}
          >
            {record.status === 'stopped' ? '已停止' : '停止做种'}
          </Button>
      )
    }
  ]

  // 加载做种统计数据和种子历史
  const loadData = async () => {
    try {
      setLoading(true)
      setError(null)

      // 1. 获取做种统计数据
      const statsRes = await userAPI.getSeedingStatus()
      const statsData = statsRes.data.data

      // 2. 获取种子历史列表
      const historyRes = await userAPI.getTorrentHistory({
        status: filter.status,
        page: filter.pagination.current,
        size: filter.pagination.pageSize
      })
      const historyData = historyRes.data.data

      // 3. 获取分享率状态
      const ratioRes = await userAPI.getShareRatioStatus()
      const ratioStatus = ratioRes.data.data

      // 处理数据
      const enrichedStats = {
        ...statsData,
        seeding_list: historyData.records || []
      }

      // 计算每个种子的分享率
      const enrichedList = enrichedStats.seeding_list.map(torrent => ({
        ...torrent,
        shareRatio: torrent.uploaded > 0 && torrent.downloaded > 0 ?
            torrent.uploaded / torrent.downloaded : 0
      }))

      setSeedingStats(enrichedStats)
      setAllTorrents(enrichedList)
      setShareRatioStatus(ratioStatus)

      // 设置分页数据
      setData({
        list: enrichedList,
        total: historyData.total
      })

    } catch (error) {
      console.error('获取数据失败:', error)
      setError('无法获取数据，将展示虚拟数据')

      // 使用虚拟数据作为后备
      setSeedingStats({
        ...DEFAULT_SEEDING_DATA,
        seeding_list: DEFAULT_SEEDING_DATA.seeding_list.map(torrent => ({
          ...torrent,
          shareRatio: torrent.uploaded / torrent.downloaded
        }))
      })
      setAllTorrents(DEFAULT_SEEDING_DATA.seeding_list.map(torrent => ({
        ...torrent,
        shareRatio: torrent.uploaded / torrent.downloaded
      })))
      setShareRatioStatus({
        share_ratio: DEFAULT_SEEDING_DATA.global_share_ratio,
        status: DEFAULT_SEEDING_DATA.global_share_ratio >= 1 ? "normal" : "warning"
      })
    } finally {
      setLoading(false)
    }
  }

  // 更新做种状态
  const handleUpdateSeedingStatus = async (torrentId) => {
    Modal.confirm({
      title: '确认停止做种?',
      icon: <ExclamationCircleOutlined />,
      content: '停止做种将不再获得魔力值奖励，是否确认？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await userAPI.updateSeedingStatus(torrentId, {
            seeding: false
          })
          message.success('已停止做种')
          // 刷新数据
          loadData()
        } catch (error) {
          message.error('操作失败: ' + (error.response?.data?.message || error.message))
        }
      }
    })
  }

  useEffect(() => {
    // 加载数据
    loadData()
  }, [filter])

  const handleStatusChange = value => {
    setFilter(prev => ({
      ...prev,
      status: value,
      pagination: { ...prev.pagination, current: 1 }
    }))
  }

  // 做种状态图形配置
  const pieConfig = {
    data: seedingStats?.seeding_list && seedingStats.seeding_list.length > 0 ?
        seedingStats.seeding_list.map(torrent => ({
          type: torrent.torrentName,
          value: torrent.uploaded
        })) : [],
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    innerRadius: 0.6,
    label: {
      type: 'inner',
      content: '{type}',
      style: {
        fontSize: 12,
        textAlign: 'center',
      },
    },
    interactions: [
      { type: 'element-active' },
    ],
    legend: {
      position: 'bottom',
    },
  }

  // 获取分享率状态信息
  const getShareRatioMessage = () => {
    if (!shareRatioStatus) return null

    switch(shareRatioStatus.status) {
      case 'restricted':
        return (
            <Alert
                message="分享率过低"
                description={shareRatioStatus.restriction?.message || "分享率低于0.5，禁止下载新种子"}
                type="error"
                showIcon
                style={{ marginBottom: 16 }}
            />
        )
      case 'warning':
        return (
            <Alert
                message="分享率警告"
                description={shareRatioStatus.restriction?.message || "分享率低于1.0，请尽快提高分享率"}
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
            />
        )
      default:
        return (
            <Alert
                message="分享率良好"
                description="您的分享率符合要求，请继续保持"
                type="success"
                showIcon
                style={{ marginBottom: 16 }}
            />
        )
    }
  }

  return (
      <div className="torrent-status">
        <Space direction="vertical" style={{ width: '100%' }}>
          {error && (
              <Alert
                  message="错误提示"
                  description={error}
                  type="error"
                  showIcon
                  closable
                  style={{ marginBottom: 16 }}
              />
          )}

          {/* 分享率状态提示 */}
          {shareRatioStatus && getShareRatioMessage()}

          {/* 添加做种状态卡片 */}
          <Card title="做种状态概览" loading={loading} bordered={false}>
            <Row gutter={16} style={{ marginBottom: 24 }}>
              <Col span={6}>
                <Statistic
                    title="做种数量"
                    value={seedingStats?.total_seeding || 0}
                    suffix="个"
                />
              </Col>
              <Col span={6}>
                <Statistic
                    title="下载数量"
                    value={seedingStats?.total_downloading || 0}
                    suffix="个"
                />
              </Col>
              <Col span={6}>
                <Statistic
                    title="总上传量"
                    value={formatBytes(seedingStats?.total_uploaded)}
                />
              </Col>
              <Col span={6}>
                <Statistic
                    title="总下载量"
                    value={formatBytes(seedingStats?.total_downloaded)}
                />
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Card title="全局分享率" size="small" style={{ height: '100%' }}>
                  <div style={{ textAlign: 'center' }}>
                    <Progress
                        type="circle"
                        percent={seedingStats?.global_share_ratio ?
                            Math.min(seedingStats.global_share_ratio * 100, 500) : 0}
                        format={percent => (
                            <div>
                              <div style={{ fontSize: 36, lineHeight: 1, marginBottom: 8 }}>
                                {seedingStats?.global_share_ratio?.toFixed(2) || '0.00'}
                              </div>
                              <div>分享率</div>
                            </div>
                        )}
                        status={seedingStats?.global_share_ratio >= 1 ? "success" : "exception"}
                        strokeColor={seedingStats?.global_share_ratio >= 1 ? "#52c41a" : "#ff4d4f"}
                        width={180}
                    />
                    <div style={{ marginTop: 16 }}>
                      {seedingStats?.global_share_ratio >= 1 ?
                          <Tag color="success">优秀表现</Tag> :
                          <Tag color="warning">请继续努力</Tag>}
                    </div>
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="种子上传分布" size="small" style={{ height: '100%' }}>
                  {seedingStats?.seeding_list && seedingStats.seeding_list.length > 0 ? (
                      <Pie
                          {...pieConfig}
                          style={{ height: 250 }}
                          loading={loading}
                      />
                  ) : (
                      <div style={{ textAlign: 'center', padding: 40 }}>
                        <span>暂无做种数据</span>
                      </div>
                  )}
                </Card>
              </Col>
            </Row>
          </Card>

          {/* 做种列表 */}
          <Card
              title={
                <div className="flex items-center">
                  <span style={{ marginRight: 16 }}>种子列表</span>
                  <Select
                      value={filter.status}
                      style={{ width: 120 }}
                      onChange={handleStatusChange}
                      disabled={!seedingStats || seedingStats.seeding_list.length === 0}
                  >
                    <Option value="all">全部状态</Option>
                    <Option value="seeding">做种中</Option>
                    <Option value="downloading">下载中</Option>
                    <Option value="completed">已完成</Option>
                    <Option value="stopped">已停止</Option>
                  </Select>
                </div>
              }
              bordered={false}
              loading={loading}
          >
            <Table
                columns={columns}
                rowKey="torrentId"
                dataSource={data.list}
                pagination={{
                  current: filter.pagination.current,
                  pageSize: filter.pagination.pageSize,
                  total: data.total,
                  showSizeChanger: true,
                  showTotal: total => `共 ${data.total} 条记录`,
                  onChange: (page, pageSize) => {
                    setFilter(prev => ({
                      ...prev,
                      pagination: { current: page, pageSize }
                    }))
                  }
                }}
                loading={loading}
                bordered
                scroll={{ x: 1200 }}
                locale={{
                  emptyText: error ? '数据加载失败' : (seedingStats?.seeding_list.length === 0 ? '暂无种子记录' : '没有匹配的种子')
                }}
            />
          </Card>
        </Space>
      </div>
  )
}